package net.hanjava.roas;


/**
 * fallback is not provided.
 * @author behumble@hanjava.net
 */
public class Translator {
    private ResourceSheet sheet;
    private int colIndex;
    private String localeKey;
    
    public Translator(ResourceSheet sheet, String localeKey) {
        this.sheet = sheet;
        this.localeKey = localeKey;
        colIndex = findLocale();
    }

    public String translate(String key) {
        int r = findIndex(key);
        String result = null;
        if(r>=0) {
            result = sheet.get(r, colIndex);
            // returns key itself, if value is not found
            if(result==null || result.length()<=0) return key;
        }
        return result;
    }

    private int findLocale() {
        int colCount = sheet.getColumnCount();
        // 0 column in a header is always empty
        for(int i=1;i<colCount;i++) {
            String colName = sheet.get(0, i);
            if(localeKey.equals(colName)) return i;
        }
        return -1;
    }

    /**
     * @return index of key, -1 if not found
     */
    private int findIndex(String key) {
        int rc = sheet.getRowCount();
        for(int i=1;i<rc;i++) {
            String v = sheet.get(i, 0);
            if(key.equals(v)) return i;
        }
        return -1;
    }
}